package com.powernobug.service.impl;

import com.powernobug.bean.model.MarketSystem;
import com.powernobug.mapper.MarketSystemMapper;
import com.powernobug.service.SystemConfigService;
import com.powernobug.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-28
 * @Description:
 */
@Service
public class SystemConfigImpl implements SystemConfigService {

    @Autowired
    MarketSystemMapper marketSystemMapper;
    private final Map<String, Object> systemConfigs = new HashMap<>();

    // 启动项目时，初始化一遍系统配置
    @PostConstruct
    public void initSystemConfigs() {
        System.out.println("系统配置初始化...");
        reloadSystemConfigs();
        System.out.println("系统配置初始化完成");
    }

    // 手动获取系统配置
    @Override
    public Map<String, Object> getSystemConfigs() {
        return systemConfigs;
    }

    // 重新加载系统配置
    @Override
    public void reloadSystemConfigs() {
        parseSystemConfigs(marketSystemMapper.selectAll().stream()
                .collect(Collectors.toMap(MarketSystem::getKeyName, MarketSystem::getKeyValue)));
    }

    private void parseSystemConfigs(Map<String, String> configMap) {
        systemConfigs.putAll(Map.of(
                Constant.CONFIG_NEW, Integer.parseInt(configMap.get("market_wx_index_new")),
                Constant.CONFIG_BRAND, Integer.parseInt(configMap.get("market_wx_index_brand")),
                Constant.CONFIG_HOT, Integer.parseInt(configMap.get("market_wx_index_hot")),
                Constant.CONFIG_TOPIC, Integer.parseInt(configMap.get("market_wx_index_topic")),
                Constant.CONFIG_CATLOG_LIST, Integer.parseInt(configMap.get("market_wx_catlog_list")),
                Constant.CONFIG_CATLOG_GOODS, Integer.parseInt(configMap.get("market_wx_catlog_goods")),
                Constant.CONFIG_SHARE, Boolean.parseBoolean(configMap.get("market_wx_share"))
        ));
    }
}
